package com.process.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.process.controller.util.Code;
import com.process.controller.util.R;
import com.process.dao.outer.CampusOffPublishVoDao;
import com.process.dao.outer.CompanyEvaluationDao;
import com.process.dao.outer.CompanyEvaluationVoDao;
import com.process.dao.pojoDao.FileDetailDao;
import com.process.dao.pojoDao.StudentDao;
import com.process.dao.team.ProcessTaskDao;
import com.process.dao.team.ProcessTaskVoDao;
import com.process.dao.voDao.CampusInnerPublishVoDao;
import com.process.dao.voDao.CampusInnerSubtaskVoDao;
import com.process.dao.voDao.CoursePublishVoDao;
import com.process.dao.voDao.StudentVoDao;
import com.process.domain.outer.CompanyEvaluationVo;
import com.process.domain.publi.*;
import com.process.domain.publish.CampusInnerPublishVo;
import com.process.domain.publish.CampusInnerSubtaskVo;
import com.process.domain.publish.CourseTaskPublishVo;
import com.process.domain.team.ProcessTask;
import com.process.domain.team.ProcessTaskVo;
import com.process.filter.JwtUtils;
import com.process.service.ExcelServ.StudentService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @ClassName: StudentController
 * @Author: 殷凡卓
 * @Date: 2023/4/26 15:34
 */
@RestController
@Slf4j
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentVoDao studentVoDao;
    @Autowired
    private CampusInnerPublishVoDao campusInnerPublishVoDao;
    @Autowired
    private CampusInnerSubtaskVoDao campusInnerSubtaskVoDao;
    @Autowired
    private ProcessTaskVoDao processTaskVoDao;
    @Autowired
    private FileStorageService fileStorageService;//注入实列
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private FileDetailDao fileDetailDao;
    @Autowired
    private CoursePublishVoDao coursePublishVoDao;

    @Autowired
    private CompanyEvaluationVoDao companyEvaluationVoDao;
    @Autowired
    private CompanyEvaluationDao companyEvaluationDao;
    @Autowired
    private CampusOffPublishVoDao campusOffPublishVoDao;

    private StudentDao studentDao;

    @GetMapping
    public R getClassStudent(ServletRequest servletRequest) {
        String username = (String) servletRequest.getAttribute("username");
        Object identity = servletRequest.getAttribute("identity");
        log.info("username" + username);
        log.info("identity" + identity);
        log.info("获取本班学生信息");
        List<Student> students = studentService.selectClassStudent(username);
        return new R(Code.GET_OK, students, "查询本班所有学生");
    }

    @GetMapping("detil")
    public R getMyDetil(ServletRequest servletRequest) {
        String username = (String) servletRequest.getAttribute("username");
        Object identity = servletRequest.getAttribute("identity");
        log.info("username" + username);
        log.info("identity" + identity);
        log.info("获取我的详细信息");
        StudentVo studentVo = studentVoDao.selectMyDetil(username);
        return new R(Code.GET_OK, studentVo, "查询我的详细信息");
    }

    @GetMapping("innerPublish")
    public R getInnerPublish(ServletRequest servletRequest) {
//        获取学生班级id
        String username = (String) servletRequest.getAttribute("username");
        Student one = studentService.getOne(new LambdaQueryWrapper<Student>().
                eq(Student::getStuPhone, username));
        long classId = one.getClassId();
        //        查询本班的innerPublish
        List<CampusInnerPublishVo> campusInnerPublishVos = campusInnerPublishVoDao.selectByClassId(classId);

        return new R(Code.GET_OK, campusInnerPublishVos, "本班的校内发布表信息");
    }

    @GetMapping("Innersubtask/{publishId}")
    public R getInnersubtask(@PathVariable long publishId, ServletRequest servletRequest) {
        List<CampusInnerSubtaskVo> campusInnerSubtaskVos = campusInnerSubtaskVoDao.selectByPublishId(publishId);

        return new R(Code.GET_OK, campusInnerSubtaskVos, "学生查看发布表详情");
    }

    @GetMapping("processTask")
    public R getProcessTask(ServletRequest servletRequest) {
        String stuPhone = (String) servletRequest.getAttribute("username");
        List<ProcessTaskVo> processTaskVos = processTaskVoDao.selectProcessTaskByStudentPhone(stuPhone);
        return new R(Code.GET_OK, processTaskVos, "学生查看过程任务");
    }

    @Autowired
    private ProcessTaskDao processTaskDao;

    @PostMapping("/upload/{processId}/{practicalId}/{evalu}")
    public R uploadPlatform(@PathVariable long processId,
                            @PathVariable String evalu,
                            @PathVariable long practicalId,
                            @RequestParam("token") String token,
                            @RequestParam("file") MultipartFile file,
                            HttpServletRequest request) {

//      判断当前时间是否是提交时间
        ProcessTask selectOne = processTaskDao.selectOne(new LambdaQueryWrapper<ProcessTask>()
                .eq(ProcessTask::getProcessId, processId));
        Date scoreStart = selectOne.getScoreStart();
        Date scoreEnd = selectOne.getScoreEnd();
        Date date = new Date();
        if (date.after(scoreEnd) || date.before(scoreStart))
            return new R(Code.SAVE_ERR, null, "当前不是上传时间");


//      获取Token中学生电话
        log.info("学生上传文件Token解析开始：");
        log.info(Long.toString(processId));
        Claims claims = null;
        try {
            //token过期后，会抛出ExpiredJwtException 异常，通过这个来判定token过期，
            claims = Jwts.parser().setSigningKey("zhongyuangong")
                    .parseClaimsJws(token.replace("\"", "")).getBody();
        } catch (ExpiredJwtException e) {
            return new R(Code.SYSTEM_ERR, null, "文件上传失败。您长时间未操作页面，请重新登录");
        }
        String username = claims.getId();
        log.info(username);

//      搜索我的历史FileDetil信息
        LambdaQueryWrapper<FileDetail> eq = new LambdaQueryWrapper<FileDetail>()
                .eq(FileDetail::getProcessId, processId)
                .eq(FileDetail::getSubmitter, username);
        FileDetail one = fileDetailDao.selectOne(eq);


        if (one != null) {
            log.info("您已上传该作业");
            int delete = fileDetailDao.delete(eq);
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPlatform("local-1")    //使用指定的存储平台
                    .putAttr("pricticalId", practicalId)
                    .putAttr("submitter", username)
                    .putAttr("mutualEvalu", evalu)
                    .putAttr("processId", processId)
                    .upload();
            return new R(Code.SAVE_OK, delete, "您已经上穿该文件,原文件被替换");
        } else {
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPlatform("local-1")    //使用指定的存储平台
                    .putAttr("pricticalId", practicalId)
                    .putAttr("submitter", username)
                    .putAttr("mutualEvalu", evalu)
                    .putAttr("processId", processId)
                    .upload();
            return new R(Code.SAVE_OK, fileInfo, "文件上传成功");

        }
    }

    @GetMapping("CoursePublish")
    public R getCoursePublish(ServletRequest servletRequest) {
        String username = (String) servletRequest.getAttribute("username");

        List<CourseTaskPublishVo> courseTaskPublishVos = coursePublishVoDao.SelectByStuPhone(username);
        return new R(Code.GET_OK, courseTaskPublishVos, "学生查看课程设计任务");
    }

    /**
     * 修改密码
     *
     * @param servletRequest
     * @return
     */
    @PutMapping("updatePassword")
    public R updatePassword(@RequestBody Password password, ServletRequest servletRequest) {
        String username = (String) servletRequest.getAttribute("username");

        Student myDetil = studentDao.selectOne(new LambdaQueryWrapper<Student>()
                .eq(Student::getStuPhone, username));
        if (password.getOldPass().equals(myDetil.getStuPassword())) {
            int update = studentDao.update(null, new LambdaUpdateWrapper<Student>()
                    .eq(Student::getStuPhone, username)
                    .set(Student::getStuPassword, password.getNewPass()));

            return new R(Code.UPDATE_OK, null, "修改密码成功！");
        } else

            return new R(Code.UPDATE_ERR, null, "旧密码输入错误！");

    }


    //lichun ---------------------------------------------------------------
    @GetMapping("/allcompanyDetailVo")
    public R getallcompanyDetailVo(ServletRequest servletRequest) {

        log.info("获取所有企业的详细信息");
        List<CompanyEvaluationVo> companyEvaluationVos = companyEvaluationVoDao.selectAllCopmanyDetailVo();
        return new R(Code.GET_OK, companyEvaluationVos, "获取所有企业的详细信息");
    }

    @GetMapping("/allMyEvaluationVo")
    public R getallMyEvaluationVo(ServletRequest servletRequest) {
        String phone = (String) servletRequest.getAttribute("username");
        List<CompanyEvaluationVo> companyEvaluationVos1 = companyEvaluationVoDao.selectAllMyEvaluatioinByMyPhone(phone);
        return new R(Code.GET_OK, companyEvaluationVos1, "获取所有学生对你的评价");
    }

    @PostMapping("/addMyEvaluation")
    public R postaddMyEvaluation(ServletRequest servletRequest,
                                 @RequestBody CompanyEvaluation companyEvaluation) {
        String phone = (String) servletRequest.getAttribute("username");

        try {
            companyEvaluation.setEvaluationDate(new Date());
            Integer integer = companyEvaluationVoDao.selectMemberIdByPhone(phone);
            companyEvaluation.setMemberId(integer);
            companyEvaluationDao.insert(companyEvaluation);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("错错错");
        }

        return new R(Code.GET_OK, null, "提交你对本企业的评价");
    }


    @GetMapping("/OuterPublish")
    public R getOuterPublish(ServletRequest servletRequest) {
//        获取学生班级id
        String username = (String) servletRequest.getAttribute("username");
        Student one = studentService.getOne(new LambdaQueryWrapper<Student>().
                eq(Student::getStuPhone, username));
        long classId = one.getClassId();


        List<CampusInnerPublishVo> campusInnerPublishVos = campusOffPublishVoDao.selectOutByClassId(classId);
        // List<CampusInnerPublishVo> campusInnerPublishVos = campusInnerPublishVoDao.selectByClassId(classId);

        return new R(Code.GET_OK, campusInnerPublishVos, "本班的校外发布表信息");
    }
}